package com.atguigu.gulimall.seckill.interceptor;

import com.atguigu.common.vo.MemberRespVo;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> threadLocal = new ThreadLocal<>();

    /**
     * 用于共享用户id和临时用户key
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        AntPathMatcher matcher = new AntPathMatcher();
        boolean match = matcher.match("/kill", uri);
        if (match) {
            MemberRespVo user = (MemberRespVo) request.getSession().getAttribute("loginUser");
            if (user == null) {
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            } else {
                threadLocal.set(user);
                return true;
            }
        }
        return true;
    }
}
